﻿using System;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Documents;
using System.Windows.Media;

using TraceView.UI;

namespace TraceView.Shared.Handlers.DefaultHandler
{
    public partial class DefaultHandlerView : IBaseHandlerView, IPrintable
    {
        public static readonly DependencyProperty TraceMessageProperty = DependencyProperty.Register("TraceMessage",
            typeof(string), typeof(DefaultHandlerView), new UIPropertyMetadata());

        public static readonly DependencyProperty LineCountProperty = DependencyProperty.Register("LineCount",
            typeof(int), typeof(DefaultHandlerView), new UIPropertyMetadata(150));

        public DefaultHandlerView(string traceMessage)
        {
            InitializeComponent();
            TraceMessage = traceMessage;
            LineCount = 150;
        }

        public string TraceMessage
        {
            get { return (string)GetValue(TraceMessageProperty); }
            set { SetValue(TraceMessageProperty, value); }
        }

        public int LineCount
        {
            get { return (int)GetValue(LineCountProperty); }
            set { SetValue(LineCountProperty, value); }
        }

        #region IBaseHandlerView Members
        public bool ContainsSearchText(string searchText)
        {
            return TraceMessage.Contains(searchText);
        }

        public string Copy()
        {
            return TraceMessage;
        }

        public string GetToastString()
        {
            var sb = new StringBuilder(TraceMessage.Substring(0, Math.Min(TraceMessage.Length, 90)));
            if(TraceMessage.Length >90)
            sb.Append("...");
            return sb.ToString();
        }
        #endregion

        public override void SetDataTemplateForLevels(int level)
        {
            switch (level)
            {
                case 1:
                    LineCount = 150;
                    break;
                case 2:
                    LineCount = 300;
                    break;
                case 3:
                    LineCount = 600;
                    break;
                case 4:
                    LineCount = TraceMessage.Length;
                    break;
                default:
                    LineCount = 150;
                    break;
            }
        }

        void IPrintable.Print(FlowDocument doc)
        {
            var para = new Paragraph {
                FontFamily = new FontFamily("Consolas")
            };

            string[] lines = TraceMessage.Split(new[] { Environment.NewLine }, StringSplitOptions.None);
            foreach (string line in lines)
            {
                para.Inlines.Add(new Run(line));
                para.Inlines.Add(new LineBreak());
            }

            doc.Blocks.Add(para);
        }
    }
}